package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import main.controle;
import util.Config;

public class Database {
    private static Database instance = null;
    private static Connection conn = null;

    public static int getTableRowCount(String table) {
        int conta = 0;
        try {
            Connection c = getInstance().getConnection();
            String sql = "select count(*) from " + table;
            Statement stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if(rs.next()) {
                conta = rs.getInt(1);
            }
            rs.close();
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
            return -1;
        }
        return conta;
    }
    
    private Database() {
        // inicializa conexão
        try {
            Config c = Config.getInstance();
            // Carregando o JDBC Driver padrão
            String driverName = c.getString("database.driver");
            Class.forName(driverName);
            // Configurando a nossa conexão com um banco de dados//
            String url = c.getString("database.url");
            String username = c.getString("database.username");        //nome de um usuário de seu BD      
            String password = c.getString("database.password");      //sua senha de acesso
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {  //Driver não encontrado
            controle.LOGGER.severe(e.getMessage());
        } catch (SQLException e) {
            //Não conseguindo se conectar ao banco
            controle.LOGGER.severe(e.getMessage());
        }
    }
    
    public Connection getConnection() throws SQLException {
        if(conn == null || !conn.isValid(0)) throw new SQLException("Conexão em estado inválido ou nulo.");
        return conn;
    }
    
    public static Database getInstance() {
        if (instance == null) {
            instance = new Database();
        }
        try {
            // Deve checar status da conexão
            if (!conn.isValid(0)) {
                // deve revalidar a conexão
                instance = null;
                instance = new Database();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        }
        return instance;
    }    
}
